package com.jyj.springbootshiro.control;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @class: com.jyj.springbootshiro.control.DemoContrl
 * @description: 测试
 * @author: jiangzengkui
 * @company: 教育家
 * @create: 2021-01-05 14:58
 */
@Controller
public class DemoContrl {
    /**
     * 通过以来注入
     */

    @RequestMapping("/index")
    public String index(){
        System.out.println("===================");
        return "index";
    }

    /**
     * 通过注解鉴权
     * @return
     */
    @RequestMapping("/user/add")
    @RequiresRoles("role1")
    @RequiresPermissions("user:create")
    public String add(){
        System.out.println("=======add============");
        return "add";
    }

    /**
     * 硬编码鉴权
     * @return
     */
    @RequestMapping("/user/update")
    public String update(){
        //硬编码鉴权
        Subject subject=SecurityUtils.getSubject();
        if(subject==null){
            System.out.println("subject==null");
        }
        else{

            //单个角色
            subject.checkRole("role1");//注意这个不会返回bool，而是通过UnauthorizedException异常
            System.out.println("role role1 is "+subject.isAuthenticated());

            //单个权限

            System.out.println("Permission[user:create]  is "+subject.isPermitted("user:updatex"));
        }
        System.out.println("=======update============");
        return "update";
    }
    @RequestMapping("/login_index")
    public String loginIndex(){
        return "login_index";
    }
    @RequestMapping("/login")
    public String login(String userName,String pwd){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(userName, pwd);
        try {
            subject.login(token); //执行登录方法，如果没有异常说明OK
            return "index";
        } catch (UnknownAccountException e) {   //用户名不存在

            return "login_index";
        } catch (IncorrectCredentialsException e) {   //密码错误

            return "login_index";
        }
    }

    /**
     * 注销
     * @return
     */
    @RequestMapping("/logout")
    public String logout(){
        //获取当前的用户
        //Subject subject = SecurityUtils.getSubject();
       // subject.logout();//注销
        return "login_index";
    }

}